package com.orifine.orm.information;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import com.orifine.orm.Information;
import com.orifine.orm.model.ColumnModel;

public class CharRandomInfo implements Information {
	private int length = 20;
	private boolean isUnqiue = false;;
	private char[] chars;
	private Map<Integer, String> valueMap = new HashMap<Integer, String>();
	
	public CharRandomInfo(){
		this.chars = defaultChars;
	}
	
	public CharRandomInfo(int length){
		this.length = length;
		this.chars = defaultChars;
	}
	
	public CharRandomInfo(char ... chars ){
		this.chars = chars;
	}
	
	public CharRandomInfo(int length, char ... chars){
		this.length = length;
		this.chars = chars;
	}
	
	@Override
	public void init(ColumnModel columnMapper) {
		if(columnMapper.getLength().getValue() != 0){
			this.length = columnMapper.getLength().getValue();
		}
		this.isUnqiue = columnMapper.getUnique().isUnique();
	}
	
	@Override
	public Object value(int index, ColumnModel columnMapper) {
		String value = valueMap.get(index);
		if(value != null){
			return value;
		} else {
			StringBuffer valueStr = new StringBuffer();
			for(int i=0; i<length; i++){
				valueStr.append(chars[random.nextInt(chars.length)]);
			}
			value = valueStr.toString();
			if(isUnqiue && valueMap.values().contains(value)){
				return value(index, columnMapper);
			} else {
				valueMap.put(index, value);
				return value;
			}
		}
	}
	
	private Random random = new Random();
	private static char[] defaultChars;
	static{
		Set<Character> charSet = new TreeSet<Character>();
		for(int i = '0';i <= '9'; i ++){
			charSet.add((char)i);
		}
		for(int i = 'a';i <= 'z'; i ++){
			charSet.add((char)i);
		}
		for(int i = 'A';i <= 'Z'; i ++){
			charSet.add((char)i);
		}
		defaultChars = new char[charSet.size()];
		int i = 0;
		for(Character c : charSet){
			defaultChars[i] = c;
			i++;
		}
	}
}
